#include "kisql.h"


kisql* kisql::instance_ = new kisql();

kisql::kisql()
{
    mysql = mysql_init(nullptr);
    if(mysql == nullptr){
        perror("mysql init err");
        exit(1);
    }
}

kisql::~kisql()
{
    if(mysql != nullptr){
        mysql_close(mysql);
    }
}

kisql* kisql::getInstance(){
    return instance_;
}

MYSQL* kisql::getMysql(){
    return mysql;
}

bool kisql::initDB(string host, string user, string passwd, string db_name){
    mysql = mysql_real_connect(mysql, host.c_str(), user.c_str(), passwd.c_str(), db_name.c_str(), 3306, NULL, 0);
    if(mysql == nullptr){
        if(mysql == nullptr){
            perror("mysql connect err");
            exit(1);
        }
    }
    cout << "connect sql ok" << endl;
    return true;
}

bool kisql::exeSQL(string sql){
    if(mysql_query(mysql, sql.c_str())){
        perror("mysql query err");
        return false;
    }else{ //select success
        result = mysql_store_result(mysql);
        if(result){
            int num_fields = mysql_num_fields(result);
            int num_rows = mysql_num_rows(result);

            for(int i = 0; i < num_rows; i++){
                row = mysql_fetch_row(result);
                if(row < 0){
                    break;
                }

                for(int j = 0; j < num_fields; j++){
                    cout << row[j] << "\t\t";
                }
                cout << endl;
            }
        }else{
            //update insert delete
            if(mysql_field_count(mysql) == 0){
                //int num_rows = mysql_affected_rows(mysql);
            }else{
                //error
                cout << mysql_error(mysql) << endl;
                return false;
            }
        }
    }
    return true;
}

void kisql::closeDB(){
    if(mysql != nullptr){
        mysql_close(mysql);
    }
}
